const jsonServer = require("json-server");
const $db = require(__dirname + "/db.json");
const server = jsonServer.create();
const middlewares = jsonServer.defaults();

const path = require("path");

server.use(
  jsonServer.defaults({
    static: path.join(__dirname, "/public"), //静态资源托管
  })
);

module.exports = async (ctx, next) => {
  // 跨域设置
  ctx.set("Access-Control-Allow-Origin", "*");
  // 请求头设置
  ctx.set(
    "Access-Control-Allow-Headers",
    `Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild,x-token,user-token`
  );
  ctx.set("Access-Control-Allow-Methods", "PUT, POST, GET, DELETE, OPTIONS");
  // 一天内不会发送options请求
  // ctx.set('Access-Control-Max-Age', '86400');
  // 预请求处理
  if (ctx.method == "OPTIONS") {
    ctx.body = 200;
  } else {
    await next();
  }
};

const router = jsonServer.router($db);
 
server.use(router);
server.use(middlewares);
server.use(jsonServer.bodyParser);
// let port = process.env.PORT;   
let port = 9007;   
server.listen(port, () => {
  console.info("服务已启动, 在 http://localhost:"+port);
});
